from pathlib import Path

from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from django.utils import timezone

from center import models
from center.models import Task
from center.tools.damage_assessment import assess
from commandCenter import settings


# Create your views here.

def index(request):
    task_list = Task.objects.all().order_by('-release_time')
    route_querySet = models.Route.objects.all()
    return render(request, "index.html", {
        "task_list": task_list,
        "route_querySet": route_querySet
    })


def route_list(request):
    return render(request, "testDB.html")


def get_task_images(request, task_id):
    # 获取任务对象
    task = get_object_or_404(Task, id=task_id)
    # 获取该任务下的所有照片的列表
    image_list = task.get_images_list()
    print(task_id)
    print(image_list)
    # 使用列表推导式拼接每个图片的完整路径
    paths = [f"{settings.MEDIA_URL}{task.imgs_path.name}/{image}" for image in image_list]
    # 将路径中的反斜杠替换为正斜杠
    paths = [path.replace("\\", "/") for path in paths]
    print(paths)  # 打印拼接后的路径
    # 返回 JSON 响应
    return JsonResponse({'images': paths})


def get_task_damage_result(request, task_id):
    # 获取任务对象
    task = get_object_or_404(Task, id=task_id)
    # 使用 Path 处理路径
    before_image_path = Path(settings.MEDIA_ROOT) / task.imgs_path.name / 'damage-before.jpg'
    after_image_path = Path(settings.MEDIA_ROOT) / task.imgs_path.name / 'damage-after.jpg'
    # 确保路径是有效的 Unicode 字符串
    before_image_path = str(before_image_path)
    after_image_path = str(after_image_path)
    print("打击前路径=" + before_image_path)
    print("打击后路径=" + after_image_path)
    ret = assess(before_image_path, after_image_path)
    return JsonResponse({'result': ret})
